package org.liyufeng.project.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.liyufeng.project.util.ParamesAPI;
import org.liyufeng.project.aes.AesException;
import org.liyufeng.project.aes.WXBizMsgCrypt;

import org.liyufeng.project.service.ChatService;
import org.liyufeng.project.service.CoreService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 请求处理的核心类
 * 
 * @author liyufeng
 * @date   20141030
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 4440739483644821986L;
	
	private static Logger log = LoggerFactory.getLogger(CoreServlet.class);
	/**
	 * 请求校验（确认请求来自微信服务器）
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
		String msg_signature = request.getParameter("msg_signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");
		// 打印请求地址
        System.out.println("request=" + request.getRequestURL());  
        
		PrintWriter out = response.getWriter();
		// 请求校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		String echostr_ret=null;
		try{
			WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(ParamesAPI.token,ParamesAPI.encodingAESKey,ParamesAPI.corpId);
			// 验证URL函数
			echostr_ret=wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr);  
		}catch (AesException e) {  
            e.printStackTrace();  
            log.error("回调连接失败",e);
        }  
		if (echostr_ret == null) {  
        	// echostr_ret为空，赋予token
			echostr_ret = ParamesAPI.token;
        }
        // 拼接请求参数
        String str = msg_signature+" "+timestamp+" "+nonce+" "+echostr;
        // 打印参数+地址+result
        log.info("回调连接失败");
        System.out.println("Exception:"+echostr_ret+" "+ request.getRequestURL()+" "+"FourParames:"+str);
        out.print(echostr_ret);
		out.close();
		out = null;
	}

	/**
	 * 请求校验与处理
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 接收参数微信加密签名、 时间戳、随机数
		String msg_signature = request.getParameter("msg_signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");

		//从请求中读取整个post数据
		InputStream inputStream = request.getInputStream();
		//commons.io.jar 方法
		String Post = IOUtils.toString(inputStream, "UTF-8");
		// Post打印结果
		System.out.println(Post);
		
		String Msg = "";
		WXBizMsgCrypt wxcpt = null;
		try {
			wxcpt = new WXBizMsgCrypt(ParamesAPI.token,ParamesAPI.encodingAESKey,ParamesAPI.corpId);
			//解密消息
			Msg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, Post);
		} catch (AesException e) {
			e.printStackTrace();
		}
		// Msg打印结果
		System.out.println("Msg打印结果：" + Msg);
		
		// 调用核心业务类接收消息、处理消息
		String respMessage = CoreService.processRequest(Msg);
		
		// respMessage打印结果
		System.out.println("respMessage打印结果：" + respMessage);
		String encryptMsg = "";
		try {
			//加密回复消息
			encryptMsg = wxcpt.EncryptMsg(respMessage, timestamp, nonce);
		} catch (AesException e) {
			e.printStackTrace();
		}
		
		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(encryptMsg);
		out.close();
	}
	@Override
	public void init() throws ServletException{
		File indexDir = new File(ChatService.getIndexDir());
		//如果索引目录不存在则创建索引
		if(!indexDir.exists())
			ChatService.createIndex();
	}
	
}
